import router from "../src/router";
import $axios from "axios";
import store from "../src/store/index";
import md5 from "js-md5";
import cookie from "js-cookie";
import {
	Message,
	Loading
} from 'element-ui';

import {
	baseUrl
} from './config.js'
let mark


const axios = $axios.create({ //初始化
	timeout: 10000,
	widthCredentials: true, //跨域携带 cookies 信息
	headers: {
		"Content-Type": "application/json;charset=utf-8"
	}
})
axios.defaults.baseURL = baseUrl;




axios.interceptors.request.use( //拦截请求
	config => {
		mark = Loading.service()
		Message({
			message: '欢迎来到 Vue2.0 cli 3.3.0  工程化项目',
			center: true,
			type: 'success'
		});
		console.log('开始拦截')
		let token = store.state.token && store.state.token != "";
		if (token) {
			config.headers.common["Authorization"] = store.state.token;
		}
		return config;
	},
	err => {
		return Promise.reject(err);
	}
);


axios.interceptors.response.use( //拦截响应
	res => {
		if (
			res.status &&
			res.status == 200 &&
			res.data &&
			res.data.code &&
			res.data.code != 200
		) {
			return Promise.reject(res.data.msg || "网络请求超时，请检查网络重新请求");
		} else {
			setTimeout(() => {
				mark.close()
			}, 2000)
			console.log('通过验证，放行')
			return Promise.resolve(res);
		}
	},
	error => {
		mark.close()
		console.log("-------1--------fail---", JSON.stringify(error.response));
		console.log("--------2-------fail---", JSON.stringify(error.response.data));
		/**
		 * 异常处理：
		 * 401\403--token失效或无权限处理，统一跳转首页；
		 * 其余错误统一返回报错信息；
		 * */
		if (
			error.response &&
			error.response.data &&
			error.response.data.code &&
			(error.response.data.code == "401" || error.response.data.code == "403")
		) {
			store.commit("DEL_USER_INFO");
			store.commit("DEL_TOKEN");
			store.commit("DEL_ROUTER");
			store.commit("INIT_MENU");
			router.push("/home");
			return Promise.reject("网络请求超时，请重新登录");
		}
		if (
			error.response &&
			error.response.status &&
			error.response.status != 200 &&
			error.response.data
		) {
			return Promise.reject(
				error.response.data.message ||
				error.response.data.msg ||
				JSON.stringify(error.response.data)
			);
		} else {
			return Promise.reject(
				JSON.stringify(error.response) || "网络请求超时，请检查网络重新请求"
			);
		}
	}
);

function getNormal(path, params) { //param为对象
	return new Promise((resolve, reject) => {
		axios.get(path, params).then(res => {
			resolve(res)
		})
	})
}


export {
	getNormal
}
